package com.rongke.doctor.web.login;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import jodd.util.StringUtil;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.commons.JsonResp;
import com.rongke.doctor.constant.DoctorErrorCode;
import com.rongke.model.doctor.DoctorUser;
import com.rongke.service.DoctorUserService;
import com.rongke.utils.Md5;

/**
 * 医生端登录controller
 * 
 * @author Administrator
 *
 */
@RestController
@RequestMapping(value = "/api/doctor")
@Transactional
public class DoctorUserController {
	private static final Logger LOGGER = Logger
			.getLogger(DoctorUserController.class);

	@Autowired
	private DoctorUserService doctorUserService;

	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public JsonResp doctorUserLogin(HttpServletRequest request, String phone,
			String checkCode) {
		LOGGER.debug("doctorUserLogin");

		if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(checkCode)) {
			return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
		}

		try {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("phone", phone);
			List<DoctorUser> doctorUserList = doctorUserService
					.selectByMap(param);
			if (CollectionUtils.isEmpty(doctorUserList)
					|| doctorUserList.get(0) == null) {
				return JsonResp.fa(DoctorErrorCode.USER_NOT_EXIST
						.getErrorCode());
			}
			DoctorUser doctorUser = doctorUserList.get(0);

			// TODO:短信验证码校验

			// 生成token
			String newToken = UUID.randomUUID().toString();
			newToken = newToken.replaceAll("-", "");
			String md5Token = Md5.md5Encode(newToken);

			doctorUser.setToken(md5Token);
			doctorUser.setGmtLogin(new Date());
			doctorUserService.updateById(doctorUser);

			Subject subject = SecurityUtils.getSubject();
			// UsernamePasswordToken token = new UsernamePasswordToken(phone,
			// "FixedPassword");
			Session session = subject.getSession();
			session.setAttribute("doctorUser", doctorUser);
			// System.out.println("startTimetamp:"
			// + DateUtils.timeDate(session.getStartTimestamp(),
			// DateUtils.YYYY_MM_DD_HH_MM_SS));
			// System.out.println("lastAccessTime:"
			// + DateUtils.timeDate(session.getLastAccessTime(),
			// DateUtils.YYYY_MM_DD_HH_MM_SS));

			request.getSession().setAttribute("doctorUserId",
					doctorUser.getDoctorUserId());

			Map<String, String> dataResult = new HashMap<String, String>();
			dataResult.put("phone", doctorUser.getPhone());
			dataResult.put("token", newToken);
			dataResult.put("userId", doctorUser.getDoctorUserId());
			return JsonResp.ok(dataResult);
		} catch (Exception e) {
			LOGGER.error("doctorUserLogin failed", e);
			return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
		}
	}

	@RequestMapping(value = "/queryOne", method = RequestMethod.GET)
	public JsonResp queryDoctorUser(String doctorUserId) {
		LOGGER.debug("queryDoctorUser");

		if (StringUtil.isEmpty(doctorUserId)) {
			return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
		}

		try {
			EntityWrapper<DoctorUser> ew = new EntityWrapper<>();
			ew.eq("doctor_user_id", doctorUserId);
			ew.eq("deleted", 0);
			List<DoctorUser> result = doctorUserService.selectList(ew);
			if (CollectionUtils.isEmpty(result)) {
				return JsonResp.ok();
			} else {
				return JsonResp.ok(result.get(0));
			}

		} catch (Exception e) {
			LOGGER.error("queryDoctorUser failed", e);
			return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
		}
	}

	// 暂时不开放医生信息修改接口
	// @RequestMapping(value = "/update", method = RequestMethod.POST)
	// public JsonResp updateDoctorUser(@RequestBody DoctorUser doctorUser) {
	// LOGGER.debug("updateDoctorUser");
	//
	// if (null == doctorUser) {
	// return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
	// }
	//
	// try {
	// EntityWrapper<DoctorUser> ew = new EntityWrapper<>();
	// ew.eq("doctor_user_id", doctorUser.getDoctorUserId());
	// doctorUserService.update(doctorUser, ew);
	//
	// JSONObject jsonObj = new JSONObject();
	// jsonObj.put("doctor_user_id", doctorUser.getDoctorUserId());
	// return JsonResp.ok(jsonObj);
	// } catch (Exception e) {
	// LOGGER.error("updateDoctorUser failed", e);
	// return JsonResp.fa(DoctorErrorCode.SYSTEM_ERROR.getErrorCode());
	// }
	// }
}